<template>
  <!--:getPopupContainer="triggerNode => triggerNode.parentNode"-->
  <!--:dropdownStyle="{ maxHeight: '300px', overflow: 'auto' }"-->
  <!--  :filter-option="filterOption"-->
  <!--  option-filter-prop="children"-->

  <a-select
    :loading="dataLoading"
    :maxTagCount="3"
    :maxTagTextLength="4"
    :showSearch="true"
    :disabled="disabled"
    :mode="mode"
    style="width: 100%"
    :placeholder="placeholder"
    :value="selVal"
    @change="selChange"
    :allowClear="allowClear"
    option-label-prop="label"

    :filter-option="false"
    @search="handleSearch"
    @popupScroll="handlePopupScroll"
  >
    <!--自定义内容-->
    <div slot="dropdownRender" slot-scope="menu" @mousedown="e => e.preventDefault()">
      <a-row :gutter="24" >
        <a-col :md="13" :sm="24" style="max-height:280px; overflow: auto">
          <!--树形数据-->
          <a-tree
            :treeData="orgTree"
            @select="selT"
            :replaceFields="{
              key: 'id',
            }"
          >
          </a-tree>
        </a-col>
        <a-col :md="11" :sm="24">
          <v-nodes :vnodes="menu" />
          <a-button
            v-if="addEnable"
            type="link"
            block
            style="font-size:10px"
            icon="plus"
            @click="hasPerm('researcher:add') & $refs.addForm.add()
            ">新增</a-button>
        </a-col>
      </a-row>
      <edit-form ref="editForm" @ok="handleOk"/>
      <add-form ref="addForm" @ok="handleOk"/>
    </div>
    <a-select-option
      v-for="item in researchers"
      :key="item.id"
      :value="item.id"
      :label="item.name"
      @contextmenu.prevent.stop="rightClick(item,$event)"
    >
      <a-popover placement="left">
        <span role="img" :aria-label="item.name">
          <a-tag v-if="item.name">{{ item.name }}</a-tag>
          <a-tag v-if="item.idcard">{{ item.idcard }}</a-tag>
        </span>
        <template slot="content">
          <a-tag v-if="item.name" color="green">{{ item.name }}</a-tag>
          <a-tag v-if="item.phone" color="cyan">{{ item.phone }}</a-tag>
          <a-tag v-if="item.idcard" color="blue">{{ item.idcard }}</a-tag>
          <a-button
            v-if="hasPerm('task:edit') & editEnable"
            style="font-size:10px"
            type="link"
            size="small"
            icon="edit"
            @click="$refs.editForm.edit(item)
            ">修改</a-button>
        </template>
      </a-popover>
    </a-select-option>
  </a-select>
</template>

<script>
  import { getOrgTree } from '@/api/modular/system/orgManage'
  // import { researcherList } from '@/api/modular/main/researcher/researcherManage'
  import { taskList } from '@/api/modular/main/task/taskManage'
  import editForm from '@/views/main/task/editForm'
  import addForm from '@/views/main/task/addForm'

  import debounce from 'lodash/debounce'

  const LOAD_NUM = 30 // 加载条数--可自定义
  /*
  *人员选择使用方法：
  *
  * 0、标签写法
  *
  *         <researcher-select
                ref="firstCompPerson"
                @handleOk="(data)=>{
                  注意要进行重新排序（data.id）
                  this.$refs.participateCompPerson.getResearcherList(data.id)
                }"
                @selChange="(value)=>{
                  const temp = this.$refs.firstCompPerson.researchers.filter(item => {
                    return value === item.id
                  })
                  if (temp.length > 0) {
                    // 赋值
                    this.form.setFieldsValue({
                      firstCompUnit: temp[0].deptId,
                      deptId: temp[0].deptId
                    })
                  }
                }"
                placeholder="请输入第一完成人"
                v-decorator="['firstCompPerson', {rules: [{required: true, message: '请选择第一完成人！'}]}]"
              />
              <researcher-select
                ref="participateCompPerson"
                @handleOk="(data)=>{
                  this.$refs.firstCompPerson.getResearcherList(data.id)
                }"
                mode="multiple"
                placeholder="请选择参与完成人"
                v-decorator="['participateCompPerson', {rules: [{required: false, message: '请选择参与完成人！'}]}]"
              />
  *
  * 1、人员选择器初始化时不再加载数据，使用者需要手动加载人员选择器中的数据
  * （1）addForm加载人员选择器数据方法如下：
  *   在add方法中添加
  *   this.$nextTick(() => {
  *     this.$refs.participateCompPerson.getResearcherList()
  *     this.$refs.firstCompPerson.getResearcherList()
  *   })
  * （2）editForm加载人员选择器数据方法如下：
  *        this.$nextTick(() => {
  *          this.$refs.participateCompPerson.getResearcherList(record.participateCompPerson)
  *          this.$refs.firstCompPerson.getResearcherList(record.firstCompPerson)
  *        })
  *  (3)index 页面 查询存在人员选择器 如果人员选择器在折叠中，那么写在 toggleAdvanced方法中，如果未折叠，那么写在created方法中
  *   this.$nextTick(() => {
          if (this.$refs.firstCompPerson) this.$refs.firstCompPerson.getResearcherList()
          if (this.$refs.participateCompPerson) this.$refs.participateCompPerson.getResearcherList()
        })
     （4） handleOk中要重新刷新数据，目的就是为了保证用户在编辑或新增时点击确定是能即使更新选中的数据
        // 刷新当前页面的研究人员
        // 搜索框的人员(有可能隐藏)
        if (this.$refs.firstCompPerson) this.$refs.firstCompPerson.resetResearchersAndTopSelVal()
        if (this.$refs.participateCompPerson) this.$refs.participateCompPerson.resetResearchersAndTopSelVal()
  *
  *  暂时可参考award获奖页面
  *
  *
  * */

  export default {
    components: {
      VNodes: {
        functional: true,
        render: (h, ctx) => ctx.props.vnodes
      },
      editForm,
      addForm
    },
    name: 'TaskSelect',
    model: {
      prop: 'value',
      event: 'change'
    },
    props: {
      // eslint-disable-next-line vue/require-default-prop
      value: {
        // eslint-disable-next-line vue/require-prop-type-constructor
        type: String | Array,
        required: false
      },
      mode: {
        type: String,
        default: 'default', // 'default' | 'multiple' | 'tags' | 'combobox'
        required: false
      },
      placeholder: {
        type: String,
        default: '请选择',
        required: false
      },
      disabled: {
        type: Boolean,
        default: false,
        required: false
      },
      allowClear: {
        type: Boolean,
        default: true,
        required: false
      },
      addEnable: {
        type: Boolean,
        default: true,
        required: false
      },
      editEnable: {
        type: Boolean,
        default: true,
        required: false
      }
    },
    data () {
      return {
        dataLoading: false,
        selVal: this.value,
        orgTree: [],
        // 原数据列表 -- 从接口获取
        oriDataList: [],
        // 已渲染的下拉列表
        researchers: [],
        // 查询条件
        param: {}
      }
    },
    watch: {
      // 监听数据变化，及时提交给父组件
      selVal: {
        deep: true,
        immediate: false, // true
        handler: function (newV, oldV) {
          // 向父组件更新
          this.$emit('change', newV, oldV)
        }
      },
      // 监听父组件数据变化，及时更新子组件
      value: {
        deep: true,
        immediate: true,
        handler: function (newV) {
          this.selVal = newV
        }
      }
    },
    created () {
      this.dataLoading = true
      getOrgTree().then(res => {
        this.orgTree = res.data
        this.dataLoading = false
      })
      // this.getResearcherList()
    },
    methods: {
      // 重新请求后台并将选中的选项置顶
      resetResearchersAndTopSelVal() {
        this.getResearcherList(this.selVal)
      },
      getResearcherList(topEle, parameter) {
        this.dataLoading = true
        taskList(parameter).then((res) => {
          this.oriDataList = res.data
          if (topEle) {
            // 需要置顶移动的元素
            const moveEleIndex = []
            this.oriDataList.forEach((item, index) => {
              if (item.id) {
                // 如果是字符串，将其转化成数组
                if (typeof topEle === 'string') {
                  topEle = topEle ? topEle.split(';') : []
                }
                // 如果是数组，那么就向移动集合中进行添加
                if (typeof topEle === 'object' && topEle.includes(item.id)) {
                  moveEleIndex.push(index)
                }
              }
            })
            // 开始移动
            if (moveEleIndex.length > 0) {
              moveEleIndex.forEach(item => {
                this.oriDataList.unshift(this.oriDataList.splice(item, 1)[0])
              })
            }
          }
          this.researchers = this.oriDataList.slice(0, LOAD_NUM)
          this.dataLoading = false
        })
      },
      selChange (value) {
        this.selVal = value
        this.$emit('selChange', value)
      },
      // 选择树的时候执行
      selT (key, event) {
        this.dataLoading = true
        if (key && key.length > 0) {
          this.param.deptId = key[0]
        } else {
          this.param.deptId = ''
        }
        this.researchers = this.oriDataListFilter().slice(0, LOAD_NUM)

        this.dataLoading = false
      },

      // filterOption(input, option) {
      //   return option.componentOptions.children[0].elm.ariaLabel.indexOf(input) >= 0
      // },

      handleSearch(val) {
        this.param.name = val
        this.researchers = this.oriDataListFilter().slice(0, LOAD_NUM)
      },

      // 滚动时触发（防止抖动）
      handlePopupScroll: debounce(function () {
        this.loadMoreData(this.oriDataListFilter())
      }, 400),

      oriDataListFilter() {
        return this.oriDataList.filter(item => {
          return ((item.deptId && this.param.deptId && item.deptId === this.param.deptId) || (!this.param.deptId)) && ((item.name && this.param.name && item.name.indexOf(this.param.name) > -1) || (!this.param.name))
        })
      },

      // 加载更多数据到select框
      loadMoreData (dataList) {
        const renderedLen = this.researchers.length // 已渲染的下拉列表长度
        const totalLen = dataList.length // 当前数据源的长度
        let addList = []
        if (renderedLen < totalLen) {
          if (renderedLen + LOAD_NUM <= totalLen) {
            addList = dataList.slice(renderedLen, renderedLen + LOAD_NUM)
          } else {
            addList = dataList.slice(renderedLen, renderedLen + (totalLen % LOAD_NUM))
          }
          this.researchers = (this.researchers).concat(addList)
        }
      },
      rightClick(item) {
        this.$refs.editForm.edit(item)
      },
      handleOk(record) {
        this.getResearcherList(record.id)
        this.$emit('handleOk', record)
      }
    }
  }
</script>

<style lang="less">
.ant-popover{
  z-index: 1050;
}
</style>
